﻿using System;
using LingDong.IndexEntities.Helper;
using NLog;

namespace LingDong.IndexMerger
{
    public class SubIndexMerger : IDisposable
    {
        #region Constructor

        public SubIndexMerger()
        {
            logger = LogManager.GetCurrentClassLogger();
            logger.Debug("SubIndexMerger Consturct.");

            if (IndexNameHelper.IndexFileAlreadyExists())
            {
                logger.Error("Index file already exits");
                throw new ArgumentException("Index file already exits");
            }

            try
            {
                IndexNameHelper.CreateIndexDirectory();

                logger.Debug("DocumentIndex Consturct.");
                documentIndex = new DocumentIndex();

                logger.Debug("DictionaryIndex Consturct.");
                dictionaryIndex = new DictionaryIndex();
            }
            catch (Exception ex)
            {
                logger.Error("Error in SubIndexMerger Consturct: {0}", ex.Message);
                throw;
            }
        }

        #endregion
        

        #region Public Methods
        
        /// <summary>
        /// Merge all sub indexs in sub index directory to one merged index
        /// </summary>
        public void Merge()
        {
            logger.Debug("SubIndexMerger Merge.");
            try
            {
                logger.Debug("DocumentIndex Merge.");
                documentIndex.Merge();

                logger.Debug("DictionaryIndex Merge.");
                dictionaryIndex.Merge(documentIndex);
            }
            catch (Exception ex)
            {
                logger.Error("Error in SubIndexMerger Merge: {0}", ex.Message);
                throw;
            }
        }

        #endregion
        

        #region Private Members

        private DocumentIndex documentIndex;
        private DictionaryIndex dictionaryIndex;
        private Logger logger;

        #endregion
        

        #region Disposable related

        ~SubIndexMerger()
        {
            Dispose();
        }

        public void Dispose()
        {
            Dispose(true);
            GC.SuppressFinalize(this);
        }

        protected virtual void Dispose(bool disposing)
        {
            // protect from being called multiple times.
            if (disposed)
            {
                return;
            }

            if (disposing)
            {
                // clean up all managed resources.
                if (documentIndex != null)
                {
                    documentIndex.Dispose();
                }
            }

            disposed = true;
        }

        private bool disposed = false;

        #endregion
    }
}
